package com.example.firstproject.service;


import com.example.firstproject.common.WrapMapper;
import com.example.firstproject.common.Wrapper;
import com.example.firstproject.util.PhoneCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class PhoneService {


    public static final String PHONE_CODE_KEY = "PHONECODE_%s_C_%s";
    public static final String PHONE_CODE_TIME = "PHONECODE_%s_T_%s";

    @Autowired
    private RedisTemplate redisTemplate;

    public Wrapper sendCode(String phoneNum,String channel){
        String timeKey =  PHONE_CODE_TIME.formatted(phoneNum,channel);
        if (redisTemplate.opsForValue().get(timeKey) == null){
            String codeKey = PHONE_CODE_KEY.formatted(phoneNum,channel);
            String phoneCode = PhoneCodeUtil.getCode(6);
            redisTemplate.opsForValue().set(codeKey,phoneCode,30, TimeUnit.SECONDS);
            log.info("用户 {} 的 {} 功能的验证码是：{}",phoneNum,channel,phoneCode);
            return WrapMapper.ok();
        }else {
            return WrapMapper.error("请勿重复发送");
        }
    }


    public boolean validCode(String phoneNum, String channel, String userCode){
        String codeKey = PHONE_CODE_KEY.formatted(phoneNum,channel);
        if (redisTemplate.opsForValue().get(codeKey) == null){
            return false;
        } else {
            String sysKey = (String) redisTemplate.opsForValue().get(codeKey);
            if (userCode.equals(sysKey)){
                return true;
            } else {
                return false;
            }
        }

    }
}

